import { list, get, add, remove, update } from '@/services/restful.api';
import { message } from 'antd';
import * as routerRedux from 'react-router-redux';
import router from 'umi/router';

export default {
  namespace: 'restfulapi',

  state: {
    data: {
      list: [],
      pagination: {},
    },
  },

  state4Detail: {

  },

  effects: {
    // 查询表格
    *fetch({ payload }, { call, put }) {
      yield put({type:'showLoading'});

      const response = yield call(list, payload);

      yield put({
        type: 'save',
        payload: response,
      });
    },
    *add({ payload, callback }, { call, put }) {
      const response = yield call(add, payload);
      yield put({
        type: 'save',
        payload: response,
      });
      if (callback) callback();
    },
    *remove({ payload, callback }, { call, put }) {
      const response = yield call(remove, payload);
      yield put({
        type: 'save',
        payload: response,
      });
      if (callback) callback();
    },
    *update({ payload, callback }, { call, put }) {
      const response = yield call(update, payload);
      yield put({
        type: 'save',
        payload: response,
      });
      if (callback) callback();
    },

    // 表单
    *submitBasicForm({ payload }, { call }) {
      const response = yield call(add, payload);
      message.success('表单提交成功');

      router.push({
        pathname: '/dev/search-table',
      });

      //yield put (routerRedux.replace('/dev/search-table'));
      /*yield put({
        type: 'save',
        payload: response,
      });
      if (callback) callback();*/
    },

    // 详情
    *get({ payload }, { call, put }) {
      const response = yield call(get, payload);
      yield put({
        type: 'show',
        payload: response,
      });
    },
  },

  reducers: {
    showLoading(state, action){
      // 设置loadding信息，使得请求数据时，展示加载动画效果
      const result = { ...state,
        loading: {spinning:true, tip:'加载中', delay:200}
      };

      return result;
    },
    save(state, action) {
      return {
        ...state,
        data: action.payload,
      };
    },
    show(state4Detail, { payload }) {
      return {
        ...state4Detail,
        ...payload,
      };
    },
  },
};
